<?php


namespace services\buss;


use common\helpers\DateHelper;
use common\helpers\RedisHelper;
use common\models\base\CommonStatus;
use common\models\base\Project;
use common\models\buss\Accounts;
use common\models\buss\Platform;
use common\models\buss\TargetAccounts;
use common\models\member\Member;
use services\base\CommonStatusService;
use services\log\LogMemberOpService;
use services\member\MemberService;
use Yii;
use common\components\Service;
use common\helpers\CommonHelper;

class TargetAccountsService extends Service
{
    /**
     * 对标账号列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getList(array $params, int $page, int $pageSize): array
    {
        $query = TargetAccounts::find()
            ->alias('ta')
            ->select(['ta.*', 'cs.name t_name', 'm.realname created_member_name', 'a.nickname accounts_name'])
            ->leftJoin(Accounts::tableName() . ' a', 'a.id = ta.accounts_id and a.status in ('.Accounts::STATUS_ENABLE.','. Accounts::STATUS_INVALID.')')
            ->leftJoin(CommonStatus::tableName() . ' cs', 'ta.t_id = cs.id and cs.type = '. CommonStatus::TYPE_ACCOUNTS)
            ->leftJoin(Member::tableName() . ' m', 'm.id = ta.created_member_id and m.status in ('.Member::STATUS_ENABLE.','. Member::STATUS_INVALID.')')
            ->where([
                'ta.status' => [
                    TargetAccounts::STATUS_ENABLE,
                    TargetAccounts::STATUS_INVALID
                ],
                'a.project_id' => array_column(MemberService::getProjectListCondition(), 'value')
            ]);
        // 开始时间
        if (isset($params['created_stime']) && $params['created_stime']) {
            $query->andWhere(['>=', 'ta.created_at', strtotime($params['created_stime'])]);
        }
        // 结束时间
        if (isset($params['created_etime']) && $params['created_etime']) {
            $query->andWhere(['<=', 'ta.created_at', strtotime($params['created_etime'] . ' 23:59:59')]);
        }
        // 搜索对标账号
        if (isset($params['keywords']) && $params['keywords']) {
            $query->andWhere(['ta.name' => $params['keywords']]);
        }
        // 平台
        if (isset($params['platform_id']) && $params['platform_id']) {
            $query->andWhere(['ta.platform_id' => $params['platform_id']]);
        }
        // 账号类型
        if (isset($params['t_id']) && $params['t_id']) {
            $query->andWhere(['ta.t_id' => $params['t_id']]);
        }
        // 状态
        if (isset($params['status']) && is_numeric($params['status'])) {
            $query->andWhere(['ta.status' => $params['status']]);
        }
        // 创建人
        if (isset($params['created_member_id']) && $params['created_member_id']) {
            $query->andWhere(['ta.created_member_id' => $params['created_member_id']]);
        }

        $orderBy = [];
        if (isset($params['order_column']) && $params['order_column']) {
            $sort = isset($params['order_sort']) && $params['order_sort'] == 'asc' ? SORT_ASC : SORT_DESC;
            switch ($params['order_column']) {
                case 'fans_num':
                    $orderBy['ta.fans_num'] = $sort;
                    break;
                case 'works_num':
                    $orderBy['ta.works_num'] = $sort;
                    break;
                case 'created_at':
                    $orderBy['ta.created_at'] = $sort;
                    break;
                case 'change_date':
                    $orderBy['ta.change_date'] = $sort;
                    break;
                default :
                    break;
            }
        }
        $orderBy['ta.status'] = SORT_DESC;
        $orderBy['ta.id'] = SORT_DESC;
        $list = $this->getListPageRes($query, $page, $pageSize, $orderBy);

        foreach ($list['list'] as &$val) {
            $platform = $val['platform_id'] ? RedisHelper::getPlatform($val['platform_id']) : '';
            $val['platform_name'] = $platform && $platform->status != Platform::STATUS_DELETE ? $platform->name : '';
            $val['created_at_str'] = DateHelper::timestampToDate($val['created_at']);
        }
        return $list;
    }

    /**
     * 状态下拉筛选项
     * @return array[]
     */
    public static function getStatusCondition(): array
    {
        return [
            ['value' => TargetAccounts::STATUS_ENABLE, 'label' => TargetAccounts::$statuss[TargetAccounts::STATUS_ENABLE]],
            ['value' => TargetAccounts::STATUS_INVALID, 'label' => TargetAccounts::$statuss[TargetAccounts::STATUS_INVALID]],
        ];
    }

    /**
     * 创建人下拉筛选项
     * @return array[]
     */
    public static function getCreatedMemberCondition(): array
    {
        $ids = TargetAccounts::find()
            ->select(['created_member_id'])
            ->where(['status' => [TargetAccounts::STATUS_ENABLE, TargetAccounts::STATUS_INVALID]])
            ->groupBy('created_member_id')
            ->column();
        return $ids ? MemberService::getListCondition($ids) : [];
    }

    /**
     * 详情数据
     * @param int $id
     * @return array
     */
    public function getInfo(int $id): array
    {
        $data = [];
        // 内容信息
        $target = TargetAccounts::findOne($id);
        if ($target) {
            $data = [
                'id' => $target->id,
                'name' => $target->name,
                'accounts_id' => $target->accounts_id,
                't_id' => $target->t_id,
                'position' => $target->position,
                'platform_id' => $target->platform_id,
                'fans_num' => $target->fans_num,
                'works_num' => $target->works_num,
            ];
        }
        $condition = [
            'account_arr' => AccountsService::getEnableList(null, $data['accounts_id'] ?? null),
            'account_type_arr' => CommonStatusService::getEditCondition(CommonStatus::TYPE_ACCOUNTS, $target['t_id'] ?? null),
            'platform_arr' => PlatformService::getEditCondition($target['platform_id'] ?? null),
        ];
        if ($target) {
            if (in_array($data['accounts_id'], array_column($condition['account_arr'], 'value')) === false) {
                $data['accounts_id'] = 0;
            }
            if (in_array($data['t_id'], array_column($condition['account_type_arr'], 'value')) === false) {
                $data['t_id'] = 0;
            }
            if (in_array($data['platform_id'], array_column($condition['platform_arr'], 'value')) === false) {
                $data['platform_id'] = 0;
            }
        }
        return array_merge($data, ['condition' => $condition]);
    }

    /**
     * 更新对标账号
     * @throws \Exception
     */
    public function updateTargetAccounts(array $params): array
    {
        $target = new TargetAccounts();
        // 是否为编辑，编辑判断排除当前ID
        $whereId = [];
        $scenario = 'create';
        $oldTarget = null;
        if ($params['id']) {
            $whereId = ['!=', 'id', $params['id']];
            // 对标账号表
            $target = TargetAccounts::findOne($params['id']);
            $oldTarget = self::getData($params['id']);
            $scenario = 'edit';
        }
        // 判断名称是否存在
        $check = TargetAccounts::find()
            ->select(['id'])
            ->where([
                'name' => $params['name'],
                'status' => TargetAccounts::STATUS_ENABLE
            ])
            ->andWhere($whereId)
            ->asArray()
            ->one();
        if ($check) {
            return CommonHelper::api(422, '对标账号已存在');
        }

        $target->name = $params['name'];
        $target->accounts_id = $params['accounts_id'] ?? '';
        $target->t_id = $params['t_id'] ?? '';
        $target->position = $params['position'] ?? '';
        $target->platform_id = $params['platform_id'];
        $target->fans_num = $params['fans_num'];
        $target->works_num = $params['works_num'];
        $target->status = $params['status'] ?? TargetAccounts::STATUS_ENABLE;
        $target->created_member_id = Yii::$app->user->identity->member_id;
        $target->operation_id = Yii::$app->user->identity->member_id;
        $target->operation_name = Yii::$app->user->identity->member->realname;
        $target->change_date = date('Y-m-d H:i:s');
        $target->saveAndCheckResult();

        // 添加日志
        LogMemberOpService::createTargetAccountsLog($scenario, $target, $oldTarget);

        return ['id' => $target->id];
    }

    /**
     * 对标账号数据
     * @param int $id
     * @return TargetAccounts|null
     */
    public static function getData(int $id): ?TargetAccounts
    {
        return TargetAccounts::findOne($id);
    }

    /**
     * 对标账号删除
     * @throws \Exception
     */
    public function deleteTargetAccounts(array $params): array
    {
        // 更新设备状态为-1
        TargetAccounts::updateAll([
            'status' => TargetAccounts::STATUS_DELETE,
            'operation_id' => Yii::$app->user->identity->member_id,
            'operation_name' => Yii::$app->user->identity->member->realname,
            'updated_at' => time()], ['id' => $params['id']]);

        // 添加日志
        LogMemberOpService::createTargetAccountsLog('delete',  self::getData($params['id']));
        return ['id' => $params['id']];
    }
}
